﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Common;
using CNCSoft.ErpApps.TMS.myclass;

namespace CNCSoft.ErpApps.TMS
{
    public partial class frmDangKyNgayNghiChoLop : Form
    {
        private SqlConnection conn;
        private DataSet ds;
        private string companyID;
        private CommonClass mine;
        private Calculate cal;
        bool signTable = false;
        bool signDetail = false;
        bool signTableNgayNghi = false;
        private bool signTableNgayThiCuaLop = false;
        private IFormatProvider culture;

        public frmDangKyNgayNghiChoLop()
        {
            InitializeComponent();
        }

        private void frmDangKyNgayNghiChoLop_Load(object sender, EventArgs e)
        {
            conn = new SqlConnection(GlobalVariable.WSInfo.ConnectionString);
            ds = new DataSet();
            companyID = GlobalVariable.WSInfo.CompanyID;
            mine = new CommonClass();
            cal = new Calculate();
            culture = new System.Globalization.CultureInfo("fr-FR", true);

            LoadControl();
        }

        private void searchLookUpEditKhoaHoc_EditValueChanged(object sender, EventArgs e)
        {
            try 
	        {	        
		        string makhoahoc = searchLookUpEditKhoaHoc.EditValue.ToString();
                LoadNgayNghiByLop(makhoahoc);

                LoadDetailOfKhoaHoc(makhoahoc);
                LoadNgayThiLop(makhoahoc);
	        }
	        catch (Exception ex)
	        {
                MessageBox.Show(ex.Message);
	        }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            TinhNgayKetThucMoi();
        }

        private void simpleButtonDangKy_Click(object sender, EventArgs e)
        {
            DangKy();
        }

        private void btnUpdateDateTest_Click(object sender, EventArgs e)
        {
            CalNewTestDate();
        }

        private void simpleButtonLamLai_Click(object sender, EventArgs e)
        {
            try
            {
                Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #region coding
        private void LoadControl()
        {
            try
            {
                LoadKhoaHoc();
                if (signTable)
                {
                    DateTime old_end_date = 
                        DateTime.Parse(ds.Tables["TableNgayNghi"].Rows[0][2].ToString(), culture, System.Globalization.DateTimeStyles.AssumeLocal);
                    lblOldEndDate.Text = old_end_date.ToShortDateString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadKhoaHoc()
        {
            try
            {
                string sql =
                @"SELECT MaKhoaHoc, TenKhoaHoc, NgayBatDau, NgayKetThuc, MaNgayTrongTuan
                    FROM DM_KHOAHOC
                    WHERE MaDonVi = '" + companyID + "'";
                mine.ExecuteDataAdapter(sql, conn, ds, "TableKhoaHoc", "MaKhoaHoc", "TenKhoaHoc", searchLookUpEditKhoaHoc);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadDetailOfKhoaHoc(string makhoahoc)
        {
            if (signDetail)
            {
                ds.Tables["TableClassDetail"].Rows.Clear();
            }
            string sql =
                @"SELECT dmkh.MaKhoaHoc, dmkh.TenKhoaHoc, 
                    CONVERT(VARCHAR, dmkh.NgayBatDau, 103), dmngaytrongtuan.MaNgayTrongTuan, dmngaytrongtuan.TenNgayTrongTuan,
                    CONVERT(VARCHAR, dmkh.NgayKetThuc, 103), dmkh.SoNgayHoc, dmgh.TenGiohoc
                    FROM DM_KHOAHOC dmkh INNER JOIN DM_NGAYTRONGTUAN dmngaytrongtuan
                    ON dmkh.MaNgayTrongTuan = dmngaytrongtuan.MaNgayTrongTuan
                    INNER JOIN DM_GIOHOC dmgh ON dmgh.MaGiohoc = dmkh.MaTimeSlot
                    WHERE MaDonVi = '" + companyID + @"'
                    AND MaKhoaHoc = '" + makhoahoc + "'";
            SqlDataAdapter da = new SqlDataAdapter(sql, conn);
            da.Fill(ds, "TableClassDetail");
            signDetail = true;

            lblClassName.Text = ds.Tables["TableClassDetail"].Rows[0][1].ToString();
            lblStartDate.Text = ds.Tables["TableClassDetail"].Rows[0][2].ToString();
            lblNgayTrongTuan.Text = ds.Tables["TableClassDetail"].Rows[0][4].ToString();
            lblGioHoc.Text = ds.Tables["TableClassDetail"].Rows[0][7].ToString();
            if (ds.Tables["TableNgayNghi"].Rows.Count <= 0)
                lblOldEndDate.Text = ds.Tables["TableClassDetail"].Rows[0][5].ToString();
            else
                lblOldEndDate.Text = ds.Tables["TableNgayNghi"].Rows[0][6].ToString();
        }

        private void LoadNgayThiLop(string makhoahoc)
        {
            try
            {
                if (signTableNgayThiCuaLop)
                {
                    ds.Tables["TableNgayThiCuaLop"].Rows.Clear();
                }
                string sql =
                    @"SELECT DISTINCT
                        dmkh.TenKhoaHoc AS N'Tên lớp',
                        dmmt.TenMonThi AS N'Tên môn thi',
                        CONVERT(VARCHAR, kqht.NgayThi, 103) AS N'Ngày thi',
                        dmmt.MaMonThi AS N'Mã môn thi'
                        FROM DM_KHOAHOC dmkh
                        LEFT OUTER JOIN Invoice_KhoaHoc invkh ON dmkh.MaKhoaHoc = invkh.MaKhoaHoc
                        LEFT OUTER JOIN Invoice_KhoaHoc_KQHT kqht ON kqht.MaHocTap = invkh.ID
                        INNER JOIN DM_MONTHI dmmt ON dmmt.MaMonThi = kqht.MaMonThi
                        WHERE dmkh.MaKhoaHoc = '" + makhoahoc + "'";
                mine.ExecDataAdapter(sql, conn, ds, "TableNgayThiCuaLop", gridControlNgayThiLop);
                signTableNgayThiCuaLop = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadNgayNghiByLop(string makhoahoc)
        {
            try
            {
                if (signTableNgayNghi)
                {
                    ds.Tables["TableNgayNghi"].Rows.Clear();
                }
                string sql =
                @"SELECT 
                    nn.ID as N'ID',
                    dmkh.TenKhoaHoc as N'Tên lớp',
                    CONVERT(VARCHAR, nn.OldEndDate, 103) N'Ngày kết thúc cũ',
                    nn.SoNgayBu as N'Số ngày bù', 
                    CONVERT(VARCHAR, nn.NgayBatDauNghi, 103) as N'Ngày bắt đầu nghỉ',
                    CONVERT(VARCHAR, nn.NgayKetThucNghi, 103) as N'Ngày kết thúc nghỉ', 
                    CONVERT(VARCHAR, nn.NewEndDate, 103) as N'Ngày kết thúc mới',
                    nn.Reason as N'Lý do được nghỉ'
                    FROM NgayNghi nn
                    INNER JOIN DM_KHOAHOC dmkh
                    ON nn.MaKhoaHoc = dmkh.MaKhoaHoc
                    WHERE nn.MaKhoaHoc = '" + makhoahoc + @"'
                    ORDER BY nn.ID DESC";
                mine.ExecDataAdapter(sql, conn, ds, "TableNgayNghi", gridControlNgayNghi);
                signTableNgayNghi = true;
                if (ds.Tables["TableNgayNghi"].Rows.Count > 0)
                {
                    signTable = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void TinhNgayKetThucMoi()
        {
            try
            {
                if (dateEditStartRestDate.Text != "")
                {
                    int tongsongay = Convert.ToInt32(ds.Tables["TableClassDetail"].Rows[0][6]);
                    DateTime enddate;
                    DateTime startrestdate = 
                        Convert.ToDateTime(dateEditStartRestDate.EditValue);
                    DateTime startdate = DateTime.Parse(lblStartDate.Text, culture, System.Globalization.DateTimeStyles.AssumeLocal);
                    
                    if(lblOldEndDate.Text != "")
                    {
                        enddate = DateTime.Parse(lblOldEndDate.Text, culture, System.Globalization.DateTimeStyles.AssumeLocal);
                    }else
                    {
                        enddate = 
                            DateTime.Parse(ds.Tables["TableClassDetail"].Rows[0][5].ToString(), culture, System.Globalization.DateTimeStyles.AssumeLocal);
                    }

                    if(ds.Tables["TableNgayNghi"].Rows.Count > 0)
                    {
                        for (int j = 0; j < ds.Tables["TableNgayNghi"].Rows.Count; j++)
                        {
                            tongsongay += Convert.ToInt32(ds.Tables["TableNgayNghi"].Rows[j][3]);
                        }
                    }

                    string mangaytrongtuan = ds.Tables["TableClassDetail"].Rows[0][3].ToString();

                    DateTime endrestdate = new DateTime();
                    string thu_startrestdate;
                    bool flag = false;
                    if (dateEditEndRestDate.Text == "")
                    {
                        thu_startrestdate = startrestdate.DayOfWeek.ToString();
                        if (mangaytrongtuan.Equals("01"))
                        {
                            if (thu_startrestdate.Equals("Monday") || thu_startrestdate.Equals("Wednesday") || thu_startrestdate.Equals("Friday"))
                            {
                                flag = true;
                                cal.CalEndDateAfterRest246(conn, ds, startrestdate, startdate, enddate, startrestdate.AddDays(1), tongsongay, dateEditNewEndDate, mangaytrongtuan, 3);
                            }
                        }
                        else if (mangaytrongtuan.Equals("02"))
                        {
                            if (thu_startrestdate.Equals("Tuesday") || thu_startrestdate.Equals("Thursday") || thu_startrestdate.Equals("Saturday"))
                            {
                                flag = true;
                                cal.CalEndDateAfterRest357(conn, ds, startrestdate, startdate, enddate, startrestdate.AddDays(1), tongsongay, dateEditNewEndDate, mangaytrongtuan, 3);
                            }
                        }
                        else if (mangaytrongtuan.Equals("20"))
                        {
                            if (thu_startrestdate.Equals("Saturday") || thu_startrestdate.Equals("Sunday"))
                            {
                                cal.CalEndDateAfterRest7CN(conn, ds, startdate, enddate, startrestdate, tongsongay, mangaytrongtuan, 2, dateEditNewEndDate);
                            }
                        }
                        else if (mangaytrongtuan.Equals("21"))
                        {
                            if (thu_startrestdate != "Saturday" && thu_startrestdate != "Sunday")
                            {
                                cal.CalEndDateAfterRestMonToFri(conn, ds, startdate, enddate, startrestdate, tongsongay, mangaytrongtuan, 5, dateEditNewEndDate);
                            }
                        }
                        if (flag == true)
                        {
                            endrestdate = startrestdate.AddDays(1);
                        }
                    }
                    else
                    {
                        endrestdate = 
                            Convert.ToDateTime(dateEditEndRestDate.EditValue);

                        // Calculate End Date After Rest 246
                        if (mangaytrongtuan.Equals("01"))
                        {
                            cal.CalEndDateAfterRest246(conn, ds, startrestdate, startdate, enddate, endrestdate, tongsongay,
                                                        dateEditNewEndDate, mangaytrongtuan, 3);
                        }

                        // Calculate End Date After Rest 357
                        if (mangaytrongtuan.Equals("02"))
                        {
                            cal.CalEndDateAfterRest357(conn, ds, startrestdate, startdate, enddate, endrestdate, tongsongay,
                                                        dateEditNewEndDate, mangaytrongtuan, 3);
                        }

                        // Calculate End Date After Rest 7CN
                        if (mangaytrongtuan.Equals("20"))
                        {
                            cal.CalEndDateAfterRest7CN(conn, ds, startdate, enddate, startrestdate, endrestdate, tongsongay,
                                                    mangaytrongtuan, 2, dateEditNewEndDate);
                        }

                        // Calculate End Date After Rest MonToFri
                        if (mangaytrongtuan.Equals("21"))
                        {
                            cal.CalEndDateAfterRestMonToFri(conn, ds, startdate, enddate, startrestdate, endrestdate, tongsongay,
                                                        mangaytrongtuan, 2, dateEditNewEndDate);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Bạn chưa nhập ngày bắt đầu nghỉ");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            } 
        }

        private void DangKy()
        {
            try
            {
                if (dateEditNewEndDate.Text != "")
                {
                    string mangaytrongtuan = ds.Tables["TableClassDetail"].Rows[0][3].ToString();
                    int songaynghitrungngayhoc = 0;
                    int songaybu = 0;
                    int tongsongay = Convert.ToInt32(ds.Tables["TableClassDetail"].Rows[0][6]);
                    // Ngày bắt đầu nghỉ
                    DateTime startrestdate = Convert.ToDateTime(dateEditStartRestDate.EditValue);

                    // Tính số ngày bù
                    if (dateEditEndRestDate.Text != "")
                    {
                        DateTime endrestdate = Convert.ToDateTime(dateEditEndRestDate.EditValue);
                        if (ds.Tables["TableNgayNghi"].Rows.Count > 0)
                        {
                            tongsongay += Convert.ToInt32(ds.Tables["TableNgayNghi"].Rows[0][3]);
                        }

                        string sql =
                            @"SELECT DATEDIFF(DAY, '" + startrestdate + "', '" + endrestdate + "')";
                        SqlDataAdapter da_songaynghi = new SqlDataAdapter(sql, conn);
                        da_songaynghi.Fill(ds, "TableSoNgayNghi");
                        int songaynghi = Convert.ToInt32(ds.Tables["TableSoNgayNghi"].Rows[0][0]);
                        ds.Tables["TableSoNgayNghi"].Rows.Clear();

                        DateTime new_startrestdate = new DateTime();
                        //-------------------------------------
                        if (mangaytrongtuan == "01")
                        {
                            if (startrestdate.DayOfWeek.ToString() == "Monday" || startrestdate.DayOfWeek.ToString() == "Wednesday" || startrestdate.DayOfWeek.ToString() == "Friday")
                            {
                                songaynghitrungngayhoc += 1;
                            }
                        }
                        else if (mangaytrongtuan == "02")
                        {
                            if (startrestdate.DayOfWeek.ToString() == "Tuesday" || startrestdate.DayOfWeek.ToString() == "Thursday" || startrestdate.DayOfWeek.ToString() == "Saturday")
                            {
                                songaynghitrungngayhoc += 1;
                            }
                        }
                        else if (mangaytrongtuan == "20")
                        {
                            if (startrestdate.DayOfWeek.ToString() == "Saturday" || startrestdate.DayOfWeek.ToString() == "Sunday")
                            {
                                songaynghitrungngayhoc += 1;
                            }
                        }
                        else if (mangaytrongtuan == "21")
                        {
                            if (startrestdate.DayOfWeek.ToString() != "Saturday" && startrestdate.DayOfWeek.ToString() != "Sunday")
                            {
                                songaynghitrungngayhoc += 1;
                            }
                        }
                        //-------------------------------------
                        for (int i = 1; i <= songaynghi; i++)
                        {
                            new_startrestdate = startrestdate.AddDays(i);
                            //-------------------------------------------
                            if (mangaytrongtuan == "01")
                            {
                                if (new_startrestdate.DayOfWeek.ToString() == "Monday" || new_startrestdate.DayOfWeek.ToString() == "Wednesday" || new_startrestdate.DayOfWeek.ToString() == "Friday")
                                {
                                    songaynghitrungngayhoc++;
                                }
                            }
                            else if (mangaytrongtuan == "02")
                            {
                                if (new_startrestdate.DayOfWeek.ToString() == "Tuesday" || new_startrestdate.DayOfWeek.ToString() == "Thursday" || new_startrestdate.DayOfWeek.ToString() == "Saturday")
                                {
                                    songaynghitrungngayhoc++;
                                }
                            }
                            else if (mangaytrongtuan == "20")
                            {
                                if (new_startrestdate.DayOfWeek.ToString() == "Saturday" || new_startrestdate.DayOfWeek.ToString() == "Sunday")
                                {
                                    songaynghitrungngayhoc++;
                                }
                            }
                            else if (mangaytrongtuan == "21")
                            {
                                if (new_startrestdate.DayOfWeek.ToString() != "Saturday" && new_startrestdate.DayOfWeek.ToString() != "Sunday")
                                {
                                    songaynghitrungngayhoc++;
                                }
                            }
                        }
                        tongsongay += songaynghitrungngayhoc;
                        songaybu += songaynghitrungngayhoc;
                    }
                    else
                    {
                        bool s = false;
                        if (mangaytrongtuan == "01")
                        {
                            if (startrestdate.DayOfWeek.ToString() == "Monday" || startrestdate.DayOfWeek.ToString() == "Wednesday" || startrestdate.DayOfWeek.ToString() == "Friday")
                            {
                                s = true;
                            }
                        }
                        else if (mangaytrongtuan == "02")
                        {
                            if (startrestdate.DayOfWeek.ToString() == "Tuesday" || startrestdate.DayOfWeek.ToString() == "Thurday" || startrestdate.DayOfWeek.ToString() == "Saturday")
                            {
                                s = true;
                            }
                        }
                        else if (mangaytrongtuan == "20")
                        {
                            if (startrestdate.DayOfWeek.ToString() == "Saturday" || startrestdate.DayOfWeek.ToString() == "Sunday")
                            {
                                s = true;
                            }
                        }
                        else if (mangaytrongtuan == "21")
                        {
                            if (startrestdate.DayOfWeek.ToString() != "Saturday" && startrestdate.DayOfWeek.ToString() != "Sunday")
                            {
                                s = true;
                            }
                        }
                        if (s == true)
                            songaybu = 1;                        
                    }

                    // Mã khóa học
                    string makhoahoc = searchLookUpEditKhoaHoc.EditValue.ToString();

                    //Old End Date
                    DateTime oldenddate;
                    if (lblOldEndDate.Text != "")
                    {
                        oldenddate = DateTime.Parse(lblOldEndDate.Text, culture, System.Globalization.DateTimeStyles.AssumeLocal);
                    }
                    else
                    {
                        oldenddate = 
                            DateTime.Parse(ds.Tables["TableClassDetail"].Rows[0][5].ToString(), culture, System.Globalization.DateTimeStyles.AssumeLocal);
                    }

                    // Lý do nghỉ
                    string reason = memoEditReason.Text;

                    // Ngày kết thúc nghỉ
                    string str_endrestdate = "";

                    if (dateEditEndRestDate.Text != "")
                    {
                        str_endrestdate = String.Format("{0:MM/dd/yyyy}", dateEditEndRestDate.EditValue);
                        string sql_insert =
                        @"INSERT INTO NgayNghi(MaKhoaHoc, OldEndDate, SoNgayBu, NgayBatDauNghi, NgayKetThucNghi, NewEndDate, Reason)
                            VALUES(@makhoahoc, @oldenddate, @songaybu, @ngaybatdaunghi, @ngayketthucnghi, @newenddate, @reason)";
                        SqlCommand cmd = new SqlCommand(sql_insert, conn);
                        cmd.Parameters.AddWithValue("@makhoahoc", makhoahoc);
                        cmd.Parameters.AddWithValue("@oldenddate", oldenddate);
                        cmd.Parameters.AddWithValue("@songaybu", songaybu);
                        cmd.Parameters.AddWithValue("@ngaybatdaunghi", startrestdate);
                        cmd.Parameters.AddWithValue("@ngayketthucnghi", str_endrestdate);
                        cmd.Parameters.AddWithValue("@newenddate", String.Format("{0:MM/dd/yyyy}", dateEditNewEndDate.EditValue));
                        cmd.Parameters.AddWithValue("@reason", reason);
                        int k = 0;
                        try
                        {
                            conn.Open();
                            k = cmd.ExecuteNonQuery();
                        }
                        finally
                        {
                            if (conn != null)
                                conn.Close();
                        }
                        if (k > 0)
                        {
                            MessageBox.Show("Thành công");
                            LoadNgayNghiByLop(makhoahoc);
                            lblOldEndDate.Text = ds.Tables["TableNgayNghi"].Rows[0][6].ToString();
                        }
                        else
                            MessageBox.Show("Thất bại");
                    }
                    else
                    {
                        string sql_insert =
                        @"INSERT INTO NgayNghi(MaKhoaHoc, OldEndDate, SoNgayBu, NgayBatDauNghi, NewEndDate, Reason)
                            VALUES(@makhoahoc, @oldenddate, @songaybu, @ngaybatdaunghi, @newenddate, @reason)";
                        SqlCommand cmd = new SqlCommand(sql_insert, conn);
                        cmd.Parameters.AddWithValue("@makhoahoc", makhoahoc);
                        cmd.Parameters.AddWithValue("@oldenddate", oldenddate);
                        cmd.Parameters.AddWithValue("@songaybu", songaybu);
                        cmd.Parameters.AddWithValue("@ngaybatdaunghi", startrestdate);
                        cmd.Parameters.AddWithValue("@newenddate", String.Format("{0:MM/dd/yyyy}", dateEditNewEndDate.EditValue));
                        cmd.Parameters.AddWithValue("@reason", reason);
                        int k = 0;
                        try
                        {
                            conn.Open();
                            k = cmd.ExecuteNonQuery();
                        }
                        finally
                        {
                            if (conn != null)
                                conn.Close();
                        }
                        if (k > 0)
                        {
                            MessageBox.Show("Thành công");
                            LoadNgayNghiByLop(makhoahoc);
                            lblOldEndDate.Text = ds.Tables["TableNgayNghi"].Rows[0][6].ToString();
                        }
                        else
                            MessageBox.Show("Thất bại");
                    }
                }
                else
                {
                    MessageBox.Show("Bạn chưa tính ngày kết thúc sau khi được học bù cho ngày nghỉ");
                }
            }
            catch (Exception ex)
            {
                
                MessageBox.Show(ex.Message);
            }
        }

        private void CalNewTestDate()
        {
            try
            {
                if (signTableNgayThiCuaLop == true && signTableNgayNghi == true)
                {
                    DataTable dtNgayThi = ds.Tables["TableNgayThiCuaLop"];
                    DataTable dtNgayNghi = ds.Tables["TableNgayNghi"];

                    int tongsongaybu = 0;
                    if (ds.Tables["TableNgayNghi"].Rows.Count > 0)
                    {
                        for (int j = 0; j < ds.Tables["TableNgayNghi"].Rows.Count; j++)
                        {
                            tongsongaybu += Convert.ToInt32(ds.Tables["TableNgayNghi"].Rows[j][3]);
                        }
                    }

                    DateTime[] datelistngaynghi = new DateTime[20];
                    DateTime[] datelistngaythi = new DateTime[10];
                    int i = 0;
                    int k = 0;
                    DateTime startrest;
                    DateTime endrest;
                    DateTime oldtest;
                    DateTime newtest = new DateTime();
                    string nametest;
                    string mangaytrongtuan = ds.Tables["TableClassDetail"].Rows[0][3].ToString();

                    if (dtNgayNghi.Rows.Count > 0 && dtNgayThi.Rows.Count > 0)
                    {
                        foreach (DataRow drnghi in dtNgayNghi.Rows)
                        {
                            if (drnghi[5].ToString() != "")
                            {
                                startrest = DateTime.Parse(drnghi[4].ToString(), culture, System.Globalization.DateTimeStyles.AssumeLocal);
                                endrest = DateTime.Parse(drnghi[5].ToString(), culture, System.Globalization.DateTimeStyles.AssumeLocal);
                                int s = 1;
                                while (s > 0)
                                {
                                    datelistngaynghi[i] = startrest;
                                    if (datelistngaynghi[i] == endrest)
                                    {
                                        i++;
                                        break;
                                    }
                                    startrest = startrest.AddDays(1);
                                    i++;
                                }
                            }
                            else
                            {
                                startrest = DateTime.Parse(drnghi[4].ToString(), culture, System.Globalization.DateTimeStyles.AssumeLocal);
                                datelistngaynghi[i] = startrest;
                                i++;
                            }
                        }

                        //----------------------------------------------
                        int insert = 0;
                        foreach (DataRow drthi in dtNgayThi.Rows)
                        {
                            bool signItem = false;
                            int j = 0;
                            newtest = DateTime.Parse(drthi[2].ToString(), culture, System.Globalization.DateTimeStyles.AssumeLocal);
                            string mamonthi = drthi[3].ToString();

                            while (j >= 0)
                            {
                                foreach (DateTime item in datelistngaynghi)
                                {
                                    if (newtest == item)
                                    {
                                        newtest = newtest.AddDays(1);
                                        while (j >= 0)
                                        {
                                            if (mangaytrongtuan == "01")
                                            {
                                                if (newtest.DayOfWeek.ToString() != "Monday"
                                                    && newtest.DayOfWeek.ToString() != "Wednesday"
                                                    && newtest.DayOfWeek.ToString() != "Friday")
                                                {
                                                    newtest = newtest.AddDays(1);
                                                }
                                                else
                                                {
                                                    break;
                                                }
                                            }

                                            else if (mangaytrongtuan == "02")
                                            {
                                                if (newtest.DayOfWeek.ToString() != "Tuesday"
                                                    && newtest.DayOfWeek.ToString() != "Thursday"
                                                    && newtest.DayOfWeek.ToString() != "Saturday")
                                                {
                                                    newtest = newtest.AddDays(1);
                                                }
                                                else
                                                {
                                                    break;
                                                }
                                            }

                                            else if (mangaytrongtuan == "20")
                                            {
                                                if (newtest.DayOfWeek.ToString() != "Saturday"
                                                    && newtest.DayOfWeek.ToString() != "Sunday")
                                                {
                                                    newtest = newtest.AddDays(1);
                                                }
                                                else
                                                {
                                                    break;
                                                }
                                            }

                                            else if (mangaytrongtuan == "21")
                                            {
                                                if (newtest.DayOfWeek.ToString() == "Saturday"
                                                    || newtest.DayOfWeek.ToString() == "Sunday")
                                                {
                                                    newtest = newtest.AddDays(1);
                                                }
                                                else
                                                {
                                                    break;
                                                }
                                            }

                                        }
                                        signItem = false;
                                    }
                                    else
                                    {
                                        signItem = true;
                                    }                                   
                                }
                                if (signItem)
                                    break;
                            }

                            if (datelistngaythi.Length > 0)
                            {
                                foreach (DateTime it in datelistngaythi)
                                {
                                    if (newtest == it)
                                    {
                                        newtest = newtest.AddDays(1);

                                        while (j >= 0)
                                        {
                                            if (mangaytrongtuan == "01")
                                            {
                                                if (newtest.DayOfWeek.ToString() != "Monday"
                                                    && newtest.DayOfWeek.ToString() != "Wednesday"
                                                    && newtest.DayOfWeek.ToString() != "Friday")
                                                {
                                                    newtest = newtest.AddDays(1);
                                                }
                                                else
                                                {
                                                    break;
                                                }
                                            }

                                            else if (mangaytrongtuan == "02")
                                            {
                                                if (newtest.DayOfWeek.ToString() != "Tuesday"
                                                    && newtest.DayOfWeek.ToString() != "Thursday"
                                                    && newtest.DayOfWeek.ToString() != "Saturday")
                                                {
                                                    newtest = newtest.AddDays(1);
                                                }
                                                else
                                                {
                                                    break;
                                                }
                                            }

                                            else if (mangaytrongtuan == "20")
                                            {
                                                if (newtest.DayOfWeek.ToString() != "Saturday"
                                                    && newtest.DayOfWeek.ToString() != "Sunday")
                                                {
                                                    newtest = newtest.AddDays(1);
                                                }
                                                else
                                                {
                                                    break;
                                                }
                                            }

                                            else if (mangaytrongtuan == "21")
                                            {
                                                if (newtest.DayOfWeek.ToString() == "Saturday"
                                                    || newtest.DayOfWeek.ToString() == "Sunday")
                                                {
                                                    newtest = newtest.AddDays(1);
                                                }
                                                else
                                                {
                                                    break;
                                                }
                                            }

                                        }
                                    }
                                }
                            }

                            datelistngaythi[k] = newtest;
                            k++;

                            //---------------------------------update new test date---------------------------
                            
                            string sql =
                                @"UPDATE Invoice_KhoaHoc_KQHT SET NgayThi = @ngaythi WHERE MaMonThi = @mamonthi";
                            SqlCommand cmd = new SqlCommand(sql, conn);
                            cmd.Parameters.AddWithValue("@ngaythi", newtest);
                            cmd.Parameters.AddWithValue("@mamonthi", mamonthi);
                            try
                            {
                                conn.Open();
                                insert = cmd.ExecuteNonQuery();
                            }
                            finally
                            {
                                if (conn != null)
                                    conn.Close();
                            }
                        }

                        if (insert > 0)
                        {
                            MessageBox.Show("Cập nhật ngày thi mới thành công");
                            string makhoahoc = searchLookUpEditKhoaHoc.EditValue.ToString();
                            LoadNgayThiLop(makhoahoc);
                        }
                        else
                        {
                            MessageBox.Show("Thất bại");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Refresh()
        {
            try
            {
                dateEditNewEndDate.Text = "";
                dateEditStartRestDate.Text = "";
                dateEditEndRestDate.Text = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

    }
}